package com.xtck.ha.fault.modules.controller;


import cn.hutool.core.date.DatePattern;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xtck.ha.fault.core.model.DsFMEAInfo;
import com.xtck.ha.fault.core.service.DsFMEAInfoService;
import com.xtck.ha.fault.framework.kafka.IKafkaProducer;
import com.xtck.ha.fault.framework.kafka.PushFaultMsg;
import com.xtck.ha.fault.framework.utils.JsonResult;
import com.xtck.ha.fault.framework.utils.MessageToJsonUtil;
import com.xtck.ha.fault.modules.dao.FmeaInfoDAO;
import com.xtck.ha.fault.modules.pojo.entity.FmeaInfo;
import com.xtck.ha.fault.modules.pojo.vo.ResultDataVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
*  controller
*
* @ClassName: FaultProcessController
* @Description: 控制层访问接口
* @author liuyuan
* @date 2025-06-17
*/
@RestController
@RequestMapping("/faultProcess")
@Api(tags={"故障流程接口管理"})
public class FaultProcessController {

    @Autowired
    IKafkaProducer iKafkaProducer;

    @Autowired
    FmeaInfoDAO fmeaInfoDAO;
    @Autowired
    DsFMEAInfoService dsFMEAInfoService;

    @PostMapping({"/doProcess"})
    @ApiOperation(value = "流程调用")
    public JsonResult<String> doProcess(@RequestBody ResultDataVo resultDataVo){
        HttpResponse getPredictDataRequest;
        try {
            getPredictDataRequest = HttpUtil.createRequest(Method.POST, "http://localhost:8099/health-mgr-back/v1.0/calculate/getResultDataList").body(JSON.toJSONString(resultDataVo)).execute();
        } catch (Exception e) {
            return JsonResult.error("调用接口失败：" + e.getMessage());
        }
        if (getPredictDataRequest.getStatus() == 200){
            JSONObject result = JSON.parseObject(getPredictDataRequest.body());
            JSONArray dataList = result.getJSONArray("data");
            Map inputParam =new HashMap<String,Object>();
            inputParam.put("dataList",dataList);
            String getFaultInfoRequestBody = JSON.toJSONString(inputParam);
            HttpResponse getFaultInfoRequest;
            try {
                getFaultInfoRequest = HttpUtil.createRequest(Method.POST, "http://localhost:9212/fault/mockFaultMod/doProcess").body(getFaultInfoRequestBody).execute();
            } catch (Exception e) {
                return JsonResult.error("调用接口失败：" + e.getMessage());
            }
            if (getFaultInfoRequest.getStatus() == 200){
                JSONObject faultInfoResult = JSON.parseObject(getFaultInfoRequest.body());
                JSONObject faultInfo = faultInfoResult.getJSONObject("data");
                DsFMEAInfo fmeaInfo = JSON.toJavaObject(faultInfo, DsFMEAInfo.class);
                fmeaInfo.setCreateTime(new Date());
                fmeaInfo.setStartTime(resultDataVo.getStartTime());
                fmeaInfo.setEndTime(resultDataVo.getEndTime());
                dsFMEAInfoService.insertT(fmeaInfo);
                SimpleDateFormat sdf = new SimpleDateFormat(DatePattern.NORM_DATETIME_PATTERN);
                PushFaultMsg pushFaultMsg = PushFaultMsg.builder()
                        .sendTime(sdf.format(new Date()))
                        .failureMode(fmeaInfo.getFailureMode())
                        .effect(fmeaInfo.getEffect())
                        .severity(fmeaInfo.getSeverity())
                        .cause(fmeaInfo.getCause())
                        .occurrence(fmeaInfo.getOccurrence())
                        .currentProcessControlPlan(fmeaInfo.getCurrentProcessControlPlan())
                        .detection(fmeaInfo.getDetection())
                        .rpn(fmeaInfo.getRpn())
                        .recommendedAction(fmeaInfo.getRecommendedAction())
                        .build();
                JsonResult jsonResult = iKafkaProducer.send("FAULT_RESULT",pushFaultMsg);
                System.out.println("发送的kafka信息为============="+ MessageToJsonUtil.toJson(pushFaultMsg));
                return jsonResult;
            }
            else {
                return JsonResult.error("调用模型计算接口失败");
            }
        }
        else{
            return JsonResult.error("查询数据失败");
        }
    }
}
